<?php

namespace App\Http\Controllers\Api;


use App\Library\OSS;
use App\Modules\Comment\Models\Comment;
use App\Modules\Coupon\Models\FullReduction;
use App\Modules\Coupon\Models\FullReductionScope;
use App\Modules\Crowd\Models\Crowd;
use App\Modules\Good\Manager;
use App\Modules\Good\Models\Good;
use App\Modules\Good\Models\GoodAttr;
use App\Modules\Good\Models\GoodAttrValue;
use App\Modules\Good\Models\GoodsDiscount;
use App\Modules\Good\Models\GoodsDiscountScope;
use App\Modules\Good\Models\GoodSpec;
use App\Modules\Good\Models\UserGoodsPoster;
use App\Modules\Order\Models\Order;
use App\Modules\Package\Models\GoodPackage;
use App\Modules\Package\Models\UserPoster;
use App\Modules\Payment\Models\WeChatPay;
use App\Modules\Rebate\Models\RebateRule;
use App\Modules\Recharge\UserBalance;
use App\Modules\Shop\GoodsList;
use App\Modules\Shop\Shop;
use App\Modules\System\Models\Brand;
use App\Modules\User\Models\Member;
use App\Modules\User\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Ramsey\Uuid\Uuid;
use App\Modules\Recharge\RechargeRecord;

class GoodController extends ApiController
{
    /**
     * 门店请求接口
     */
    public function getGoodListShop(Request $request)
    {
        $this->validate($request, [
            'offset'            => 'nullable|integer',
            'count'             => 'nullable|integer',
            'sort'              => 'nullable|string',
            'shop_id'           => 'nullable|integer',
            'category'          => 'nullable|string',
            'category_id'       => 'nullable|string',//二级分类  查询不按照id，按照名字
            'first_category_id' => 'nullable|integer',
            'screen'            => 'nullable|array',
            'name'              => 'nullable|string',
            'brand_id'          => 'nullable|string',
        ]);
        $offset          = $request->input('offset', 0);
        $count           = $request->input('count', 10);
        $sort            = $request->input('sort');
        $shopId          = $request->input('shop_id');
        $category        = $request->input('category');
        $screen          = $request->input('screen');
        $name            = $request->input('name');
        $categoryId      = $request->input('category_id');
        $firstCategoryId = $request->input('first_category_id');
        $brandId         = $request->input('brand_id');

        $query = Good::query()
            ->join('shops', 'shops.id', '=', 'goods.shop_id')
            ->leftJoin('categories', 'categories.id', '=', 'goods.category_id')
            ->leftJoin('brands', 'brands.id', '=', 'goods.brand_id')
            ->where('shops.status', Shop::STATUS_OPEN)
            ->where('goods.status', Good::STATUE_ON)
            ->when(!empty($categoryId), function ($query) use ($categoryId) {
                return $query->where('goods.second_category_name', 'like', '%' . $categoryId . '%');
            })
            ->when(!empty($shopId), function ($query) use ($shopId) {
                return $query->where('goods.shop_id', $shopId);
            })
            ->when(!empty($brandId), function ($query) use ($brandId) {
                return $query->where('brands.name', $brandId);
            })
            ->select("goods.*")
            ->offset($offset)
            ->limit($count);
        if (!empty($name)) {
            $query->where(function ($query) use ($name) {
                return $query->where('goods.name', 'like', '%' . $name . '%')
                    ->orWhere('goods.keywords', 'like', '%' . $name . '%')
                    ->orWhere('categories.name', 'like', '%' . $name . '%')
                    ->orWhere('brands.name', 'like', '%' . $name . '%');
            });
        }
        // if ($firstCategoryId || $categoryId || $brandId) {
        //     $query->where(function ($query) use ($firstCategoryId, $categoryId, $brandId) {
        //         return $query->where('goods.first_category_id', $firstCategoryId)
        //                      ->orWhere('goods.category_id', $categoryId)
        //                      ->orWhere('goods.brand_id', $brandId);
        //     });
        // }
        if (isset($screen['min']) && !empty($screen['min'])) {
            $query->where('goods.price', ">=", $screen['min']);
        }
        if (isset($screen['max']) && !empty($screen['max'])) {
            $query->where('goods.price', "<=", $screen['max']);
        }
        if (!empty($shopId)) {
            $query->where('goods.shop_id', $shopId);
        }

        switch ($sort) {
            case "createdAt":
                $query->orderByDesc('goods.created_at');
                break;
            case "priceDesc":
                $query->orderByDesc('goods.price');
                break;
            case "priceAsc":
                $query->orderBy('goods.price', 'asc');
                break;
            case "salesVolume":
                $query->orderBy('goods.sales_volume', 'asc');
                break;
            case "visitor":
                $query->orderBy('goods.visitor', 'desc');
                break;
        }
        $query->orderBy('goods.sort', 'desc');
        $re = $query->get()
            ->map(function ($item) {
                $cover = [];
                if (!empty($item->cover)) {
                    foreach ($item->cover as $value) {
                        $cover = OSS::instance()->getUrl($value);
                    }
                }
                return [
                    'id'                => $item->id,
                    'name'              => $item->name,
                    'shop_id'           => $item->shop_id,
                    'first_category_id' => $item->first_category_id,
                    'category_id'       => $item->category_id,
                    'brand_id'          => $item->brand_id,
                    'visitor'           => $item->visitor,
                    'keywords'          => $item->keywords,
                    'share_number'      => $item->share_number,
                    'cover'             => $cover,
                    'list_cover'        => empty($item->list_cover) ? "" : OSS::instance()->getUrl($item->list_cover),
                    'display_price'     => $item->display_price,
                    'price'             => $item->price,
                    'stock'             => $item->stock,
                    'sales_volume'      => $item->sales_volume + $item->virtual_sales_volume,
                    'is_free'           => $item->is_free,
                ];
            });

        return $this->success($re);
    }

    /**
     * 商城请求接口
     */
    public function getGoodList(Request $request)
    {
        $this->validate($request, [
            'offset'      => 'nullable|integer',
            'count'       => 'nullable|integer',
            'sort'        => 'nullable|string',
            'shop_id'     => 'nullable|integer',
            'category'    => 'nullable|string',
            'category_id' => 'nullable|string',//二级分类  查询不按照id，按照名字
            'screen'      => 'nullable|array',
            'name'        => 'nullable|string',
            'brand_id'    => 'nullable|string',
        ]);
        $offset     = $request->input('offset', 0);
        $count      = $request->input('count', 10);
        $sort       = $request->input('sort');
        $shopId     = $request->input('shop_id');
        $category   = $request->input('category');
        $screen     = $request->input('screen');
        $name       = $request->input('name');
        $categoryId = $request->input('category_id');
        $brandId    = $request->input('brand_id');

        $query = Good::query()
            ->join('shops', 'shops.id', '=', 'goods.shop_id')
            ->leftJoin('categories', 'categories.id', '=', 'goods.category_id')
            ->leftJoin('brands', 'brands.id', '=', 'goods.brand_id')
            ->where('shops.status', Shop::STATUS_OPEN)
            ->where('goods.status', Good::STATUE_ON)
            ->when(!empty($categoryId), function ($query) use ($categoryId) {
                return $query->where('goods.second_category_name', 'like', '%' . $categoryId . '%');
            })
            ->when(!empty($brandId), function ($query) use ($brandId) {
                return $query->where('brands.name', $brandId);
            })
            ->select("goods.*", 'shops.name as shop_name')
            ->offset($offset)
            ->limit($count);
        if (!empty($name)) {
            $query->where(function ($query) use ($name) {
                return $query->where('goods.name', 'like', '%' . $name . '%')
                    ->orWhere('goods.keywords', 'like', '%' . $name . '%')
                    ->orWhere('categories.name', 'like', '%' . $name . '%')
                    ->orWhere('brands.name', 'like', '%' . $name . '%');
            });
        }
        if (isset($screen['min']) && !empty($screen['min'])) {
            $query->where('goods.price', ">=", $screen['min']);
        }
        if (isset($screen['max']) && !empty($screen['max'])) {
            $query->where('goods.price', "<=", $screen['max']);
        }
        if (!is_null($shopId)) {
            $query->where('goods.shop_id', $shopId);
        }
        if (!is_null($category)) {
            $query->where('goods.category', $category);
        } elseif (is_null($shopId)) {
            $query->where('goods.category', "!=", "礼服租售");
        }
        switch ($sort) {
            case "createdAt":
                $query->orderByDesc('goods.created_at');
                break;
            case "priceDesc":
                $query->orderByDesc('goods.price');
                break;
            case "priceAsc":
                $query->orderBy('goods.price', 'asc');
                break;
            case "salesVolume":
                $query->orderBy('goods.sales_volume', 'asc');
                break;
            case "visitor":
                $query->orderBy('goods.visitor', 'desc');
                break;
        }

        $query->orderBy('goods.sort', 'desc');
        $re = $query->get()
            ->map(function ($item) {
                $cover = [];
                if (!empty($item->cover)) {
                    foreach ($item->cover as $value) {
                        $cover = OSS::instance()->getUrl($value);
                    }
                }
                return [
                    'id'            => $item->id,
                    'category'      => $item->category,
                    'name'          => $item->name,
                    'visitor'       => $item->visitor,
                    'keywords'      => $item->keywords,
                    'share_number'  => $item->share_number,
                    'cover'         => $cover,
                    'list_cover'    => empty($item->list_cover) ? "" : OSS::instance()->getUrl($item->list_cover),
                    'display_price' => $item->display_price,
                    'price'         => $item->price,
                    'stock'         => $item->stock,
                    'sales_volume'  => $item->sales_volume + $item->virtual_sales_volume,
                    'is_free'       => $item->is_free,
                    'top_category_id' => $item->top_category_id,
                    'shop_name' => $item->shop_name,
                ];
            });
        return $this->success($re);
    }


    public function detail(Request $request)
    {
        $this->validate($request, [
            'id' => 'required|integer',
        ]);
        $id = $request->input('id');
        $user = $this->getUser();
        /** @var Good $good */
        $good = Good::query()->find($id);
        if (is_null($good)) {
            return $this->fail('货物以下架');
        }
        $attr = GoodAttr::query()
            ->where('good_id', $id)
            ->orderBy('sort', 'desc')
            ->get()
            ->keyBy('id');
        $attrValue = [];
        GoodAttrValue::query()
            ->where('good_id', $id)
            ->whereIn('good_attr_id', $attr->pluck('name')->all())
            ->get()
            ->map(function ($item) use (&$attrValue, $attr) {
                $attrValue[$attr->get($item->good_attr_id)->name][] = $item->value;
            });
        $spec = GoodSpec::query()
            ->where('good_id', $id)
            ->get()
            ->map(function ($item) {
                return [
                    'id' => $item->id,
                    'param' => $item->param,
                    'price' => $item->price,
                    'prepay_price' => $item->prepay_price,
                    'stock' => $item->stock,
                ];
            });
        $cover = [];
        if (!empty($good->cover)) {
            foreach ($good->cover as $value) {
                $cover[] = OSS::instance()->getUrl($value);
            }
        }
        $hasBuy = Order::query()
            ->where('user_id', $user->id)
            ->where('link_id', $good->id)
            ->where('type', 'good')
            ->where('status', Order::STATUS_PAID)
            ->count();
        $re = [
            'shop_id' => $good->shop_id,
            'name' => $good->name,
            'tag' => $good->tag,
            'cover' => $cover,
            'video' => $good->video,
            'display_price' => $good->display_price,
            'description' => $good->description,
            'price' => $good->price,
            'sales_volume' => $good->sales_volume + $good->virtual_sales_volume,
            'is_free' => $good->is_free,
            'attr' => $attr->pluck('name')->all(),
            'attrValue' => $attrValue,
            'spec' => $spec,
            'end_time' => $good->end_time,
            'buy_limit' => $good->buy_limit,
            'has_buy' => $hasBuy,
            'status' => $good->status,
        ];
        return $this->success($re);
    }

    //查询服务标签
    public function getTag(Request $request){
        $this->validate($request, [
            'id' => 'required|integer',
        ]);
        $id = $request->input('id');
        $good = Good::query()->where('id', $id)->first('tag_id');
        $tag_id = !empty($good->tag_id) ? explode(',', $good->tag_id) : [];
        $data = DB::table('tags')->whereIn('id', $tag_id)->get(['name', 'id', 'describe', 'icon']);
        
        return $this->success($data);
    }

    public function createOrder(Request $request)
    {
        $this->validate($request, [
            'spec' => 'required|array',
            'mobile' => 'required|string',
            'name' => 'nullable|string',
            'address' => 'nullable|string',
            'delivery' => 'nullable|integer',
            'is_prepay' => 'nullable|boolean',
            'referrer_id' => 'nullable|integer',
            'remark' => 'nullable|string',
            'has_discount' => 'nullable|boolean'
        ]);
        $user = $this->getUser();
        $spec = $request->input('spec');
        $couponId = $request->input('coupon_id');
        $mobile = $request->input('mobile');
        $name = $request->input('name');
        $address = $request->input('address');
        $delivery = $request->input('delivery', 0);
        $isPrepay = $request->input('is_prepay', 0);
        $referrerId = $request->input('referrer_id');
        $remark = $request->input('remark', null);
        $hasDiscount = $request->input('has_discount', 0);
        $payType = $request->input('pay_type', 0);// 支付方式, 1混合支付 ，0正常支付
        $goodsId = $request->input('goods_id');
        $balance_pay = $request->input('balance_pay', 0);//混合支付中，使用充值支付的钱数

        $param = [
            'name' => $name,
            'mobile' => $mobile,
            'address' => $address,
            'delivery' => $delivery,//是否到店自取：0是、1未发货、2已发货
            'is_prepay' => $isPrepay,//是否全款支付：0全款、1定金
            'remark' => $remark,
            'has_discount' => $hasDiscount,//是否有折扣
        ];

        $balanceParam = [
            'is_balance'  => (int)$payType,// 是否使用充值支付，1，混合支付   0非混合支付，正常支付
            'balance_pay' => (int)$balance_pay,
        ];

        /**
         * 用户信息、商品信息、推荐人、优惠券、地址信息
         * spec = [店铺ID=>[商品规格ID=>数量]];
         *
         * $balanceParam  混合支付参数
         */
        $order = Manager::createOrder($user, $spec, $referrerId, $couponId, $param, $balanceParam);

        /**
         * 充值支付，减去相关充值余额，或增加充值余额，并增加记录 
         */
        if ($payType == 1 && count($order->order_id) < 2) { //余额支付

            $shop_id = array_keys($spec);
            $order_id = $order->order_id;

            //获取当前用户当前店铺的余额
            $userBalance = UserBalance::query()->where(["user_id" => $user->id, "shop_id" => $shop_id[0]])->first();
            if (!$userBalance || $userBalance->balance <= 0 || $userBalance->balance < ($order->getPrice() / 100)) { //余额不足
                return $this->fail("您在当前商户可用余额不足!");
            } else {
                $goods = Good::query()
                            ->where('id', $goodsId)
                            ->select(['is_balance_pay','is_recharge','recharge_money'])
                            ->first();
                if ($goods->is_balance_pay != 1) {
                    return $this->fail("该商品不支持余额支付");
                }

            }
        }

        if ($order->getPrice() > 0) {
            $params = WeChatPay::getParameters($order->getType(), $order->pay_no, $order->title, $order->getPrice(), $user);
        } else {
            $params = null;
            $order->active(0);
        }
        if (empty($user->name)) {
            $user->name = $name;
            $user->save();
        }
        return $this->success([
            'id' => $order->id,
            "order_id" => $order->order_id,
            'params' => $params,
        ]);
        
    }

    public function getDiscount(Request $request)
    {
        $this->validate($request, [
            'id' => 'required|integer',
            'share_user_id' => 'nullable|integer',
        ]);
        $id = $request->input('id');
        $shareUserId = $request->input('share_user_id');
        $user = $this->getUser();
        $goods = Good::query()->find($id);

        $re = [
            'full_reduction' => null,
            'discount' => null,
            'gift' => null,
        ];

        /**
         * 获取该商品或套系 是否支持余额支付, 以及相关赠送余额功能
         * @author Ezreal丶<571265160@qq.com>
         * @date 2021.08.12
         */
        $re['balance'] = [
            'is_balance'     => $goods->is_balance_pay,
            'is_recharge'    => $goods->is_recharge,
            'recharge_money' => $goods->recharge_money / 100,
        ];

        // if ($user->level < 1) {
        //     if (empty($shareUserId)) {
        //         return $this->success($re);
        //     }
        //     $shareUser = User::query()->find($shareUserId);
        //     if ($shareUser->level < 2) {
        //         if (!Member::query()
        //             ->where('user_id', $shareUserId)
        //             ->where('shop_id', $goods->shop_id)
        //             ->exists()) {
        //             return $this->success($re);
        //         }
        //     }
        // } elseif ($user->level == 1 && !Member::query()
        //         ->where('user_id', $user->id)
        //         ->where('shop_id', $goods->shop_id)
        //         ->exists()) {
        //     return $this->success($re);
        // }
        
        // 判断当前用户是否是当前商品所属门店的返利会员
        $isMember = Member::query()->where('user_id', $user->id)->where('shop_id', $goods->shop_id)->exists();
        if (empty($shareUserId)) {// 如果没有用户分享进来
            if ($user->level == 0) {// 注册用户
                return $this->success($re);
            }

            if ($user->level == 1 && !$isMember) {// 返利会员 且 不是当前门店商品的返利会员
                return $this->success($re);
            }
        }


        $re['gift'] = $goods->getGift();
        $scope = GoodsDiscountScope::query()
                    ->where('type', Good::class)
                    ->where('link_id', $id)
                    ->get();

        if (!$scope->isEmpty()) { 
            $re['discount'] = GoodsDiscount::query()
                ->whereIn('id', $scope->pluck('goods_discount_id')->all())
                ->get();
        } else {
            $full = FullReductionScope::query()
                ->where('type', Good::class)
                ->where('link_id', $id)
                ->get();
            if (!is_null($full)) {
                $re['full_reduction'] = FullReduction::query()
                    ->whereIn('id', $full->pluck('full_reduction_id')->all())
                    ->get();
            }
        }

        

        return $this->success($re);
    }

    public function crowd(Request $request)
    {
        $this->validate($request, [
            'spec_id' => 'required|integer',
            'number' => 'required|integer',
        ]);
        $user = $this->getUser();
        $specId = $request->input('spec_id');
        $number = $request->input('number');
        $referrerId = $user->referrer_id;
        $spec = GoodSpec::query()->find($specId);
        if (is_null($number)) {
            return $this->fail('id错误');
        }
        /** @var Good $good */
        $good = Good::query()->find($spec->good_id);
        if ($good->status == Good::STATUE_OFF) {
            return $this->fail('商品已下架');
        }
        DB::beginTransaction();
        $spec->decrement('stock');
        if ($spec->stock < 0) {
            DB::rollBack();
            return $this->fail('库存不足');
        }
        $crowd = Crowd::query()
            ->create([
                'no' => Crowd::getNo(),
                'shop_id' => $good->shop_id,
                'user_id' => $user->id,
                'referrer_id' => $referrerId,
                'cover' => $good->cover[0] ?? "",
                'title' => $good->name,
                'type' => Crowd::TYPE_GOOD,
                'link_id' => $good->id,
                'detail' => [
                    'id' => $specId,
                    'price' => $spec->price,
                    'param' => $spec->param,
                ],
                'number' => $number,
                'price' => $spec->price * $number,
                'status' => Crowd::STATUS_PROGRESSION,
            ]);
        DB::commit();
        return $this->success($crowd);
    }

    public function updateShoppingCart(Request $request)
    {
        $user = $this->getUser();
        $data = $request->input('data', null);
        Manager::updateShoppingCart($user, $data);
        return $this->success();
    }

    public function getShoppingCart(Request $request)
    {
        $user = $this->getUser();
        $re = Manager::getShoppingCart($user);
        return $this->success($re);
    }

    public function visitor(Request $request)
    {
        $this->validate($request, [
            'id' => 'required|integer',
        ]);
        $id = $request->input('id');
        /** @var Good $good */
        $good = Good::query()->find($id);
        $good->increment('visitor');
        GoodsList::query()->where('goods_type', GoodsList::TYPE_GOOD)->where('link_id', $good->id)->increment('visitor');
        Shop::query()
            ->where('id', $good->shop_id)
            ->increment('visitor');
        return $this->success();
    }

    public function share(Request $request)
    {
        $this->validate($request, [
            'id' => 'required|integer',
        ]);
        $id = $request->input('id');
        $user = $this->getUser();
        Good::query()->find($id)->increment('share_number');
        $user->increment('share');
        return $this->success();
    }

    public function getCommentCount(Request $request)
    {
        $this->validate($request, [
            'id' => 'required|integer',
        ]);
        $id = $request->input('id');
        $count = Comment::query()
            ->where('type', Order::TYPE_GOOD)
            ->where('link_id', $id)
            ->where('is_show', 1)
            ->selectRaw('count(1) as count, count(if(score > 3, 1, null)) as favorable')
            ->first();
        return $this->success($count);
    }

    public function getComments(Request $request)
    {
        $this->validate($request, [
            'id' => 'required|integer',
            'offset' => 'integer',
            'count' => 'integer',
        ]);
        $id = $request->input('id');
        $offset = $request->input('offset', 0);
        $count = $request->input('count', 10);

        $comment = Comment::query()
            ->where('type', Order::TYPE_GOOD)
            ->where('link_id', $id)
            ->where('is_show', 1)
            ->orderBy('created_at', 'desc')
            ->offset($offset)
            ->limit($count)
            ->get();
        $user = User::query()
            ->whereIn('id', $comment->pluck('user_id')->all())
            ->get()
            ->keyBy('id');

        // 商家回复
        $aCommentChild = Comment::query()
            ->whereIn('pid', $comment->pluck('id')->all())
            ->get(['id','pid','content'])
            ->keyBy('pid');

        $re = $comment->map(function ($item) use ($user, $aCommentChild) {
            if (!empty($item->image)) {
                $tmp = [];
                foreach ($item->image as $value) {
                    $tmp[] = OSS::instance()->getUrl($value);
                }
                $item->image = $tmp;
            }
            return [
                'id'               => $item->id,
                'score'            => $item->score,
                'nickname'         => $user->get($item->user_id)->nickname,
                'avatar'           => $user->get($item->user_id)->avatar,
                'content'          => $item->content ?? "没有评价内容",
                'image'            => $item->image,
                'created_at'       => $item->created_at->toDateTimeString(),
                'child'            => !empty($aCommentChild->get($item->id)) ? $aCommentChild->get($item->id) : '',
                'system_reply'     => $item->system_reply,
                'system_responder' => $item->system_responder,
            ];
        });
        return $this->success($re);
    }

    /**
     * 生成海报方法   原来的， 已废弃
     */
    public function getPosterOld(Request $request)
    {
        $this->validate($request, [
            'id' => 'required|integer',
        ]);
        $id = $request->input('id');
        $user = $this->getUser();

        $poster = UserGoodsPoster::query()
            ->firstOrCreate([
                'user_id' => $user->id,
                'good_id' => $id,
            ]);
        // if (!empty($poster->url)) {
        //     return $this->success($poster->url);
        // }
        $good = Good::query()
            ->where('id', $id)
            ->first();
        if (empty($good->share_bg)) {
            return $this->success();
        }
        // if (empty($poster->qr_code)) {
        $key = Manager::getMiniProgramCode($user, $poster);
        $poster->qr_code = $key;
        // } else {
        //    $key = $poster->qr_code;
        // }
        $qrCode = rtrim(strtr(base64_encode($key . "?x-oss-process=image/resize,w_136"), '+/', '-_'), '=');
        $position = ['x' => 480, 'y' => 890];
        $position = "x_" . $position['x'] . ",y_" . $position['y'];
        $action = "/watermark,image_" . $qrCode . ",g_nw," . $position;

        $avatar = rtrim(strtr(base64_encode($user->avatar_key . "?x-oss-process=image/resize,w_68/rounded-corners,r_34"), '+/', '-_'), '=');
        $position = ['x' => 20, 'y' => 980];
        $position = "x_" . $position['x'] . ",y_" . $position['y'];
        $action .= "/watermark,image_" . $avatar . ",g_nw," . $position;

        $name = !empty($user->name) ? $user->name : $user->nickname;
        $text = rtrim(strtr(base64_encode($name), '+/', '-_'), '=');
        $position = ['x' => 105, 'y' => 1002];
        $position = "x_" . $position['x'] . ",y_" . $position['y'];
        $action .= "/watermark,text_{$text},type_ZmFuZ3poZW5naGVpdGk=,size_30,color_FFFFFF,g_nw," . $position;

        $re = OSS::instance()->getUrl($good->share_bg) . "?x-oss-process=image{$action}";
        $tmpName = tempnam(sys_get_temp_dir(), "poster-");
        copy($re, $tmpName);
        $aimKey = "poster/{$user->id}/{$id}.png";
        OSS::instance()->storeFile($aimKey, $tmpName);
        // $poster->url = OSS::instance()->getUrl($aimKey);
        $poster->save();
        return $this->success(OSS::instance()->getUrl($aimKey));
    }

    public function getRebateRule(Request $request)
    {
        $this->validate($request, [
            'id' => 'required|integer',
            'spec_id' => 'nullable|integer',
        ]);
        $id = $request->input('id');
        $specId = $request->input('spec_id');

        $query = GoodSpec::query()
            ->where('good_id', $id);
        if (!empty($specId)) {
            $query->where('id', $specId);
        }
        $re = $query->get()
            ->map(function ($item) {
                return [
                    'level1_rebate' => $item->level1_rebate,
                    'level2_rebate' => $item->level2_rebate,
                    'level3_rebate' => $item->level3_rebate,
                    'level4_rebate' => $item->level4_rebate,
                    'level_2_3_rebate' => $item->level_2_3_rebate
                ];
            });
        return $this->success($re);
    }

    public function getBrand(Request $request)
    {
        $this->validate($request, [
            'offset' => 'required|integer',
            'count' => 'required|integer',
            'parent' => 'nullable|string',
        ]);
        $offset = $request->input('offset', 0);
        $count = $request->input('count', 10);
        $parent = $request->input('parent');
        $re = Brand::query()
            ->when(!empty($parent), function ($item) use ($parent) {
                return $item->where('parent', $parent);
            })
            ->orderBy('sort', 'desc')
            ->offset($offset)
            ->limit($count)
            ->get()
            ->toArray();

        $data = [];
        if (!empty($re)) {
            foreach ($re as $key => $value) {
                $data[$value['name']] = [
                    'id'      => $value['id'],
                    'name'    => $value['name'],
                    'parent'  => $value['parent'],
                    'pid'     => $value['pid'],
                    'shop_id' => $value['shop_id'],
                ];
            }
        }
        return $this->success($data);
    }

    //检查用户是否为集团用户
    public function checkUser(Request $request){
        $this->validate($request, [
            'user_id' => 'required|integer',
            'shop_id' => 'required|integer',
        ]);
        $user_id = $request->input('user_id', 0);//登录人员id
        $shop_id = $request->input('shop_id', 0);//商品所属门店id

        // 获取推荐人所属门店的所在集团id
        $shopIds = DB::table('users')->where('id', $user_id)->first('shop_id');
        $aUserInGroupId = DB::table('shops')->where('group_id', '!=', 0)->whereIn('id', json_decode($shopIds->shop_id))->get()->pluck('group_id')->all();
        $aUserInGroupId = array_unique($aUserInGroupId);
            
        // 获取商品id所在门店的所在集团id
        $shop_info = DB::table('shops')->where('id', $shop_id)->first();
        $shop_group_id = $shop_info->group_id;

        if (!in_array($shop_group_id, $aUserInGroupId)) {
            // 非本集团或商家职员奖励金额
            $flag = false;
        }else{
            // 本集团或商家职员奖励金额
            $flag = true;
        }
        
        return $this->success($flag);
    }

    /**
     * 生成海报方法 新的
     */
    public function getPoster(Request $request)
    {
        $this->validate($request, [
            'id' => 'required|integer',
        ]);

        // 文件路径 本地测试
        $dir = public_path();
        $dir = str_replace('\\', '/', $dir);
        $dir .= '/';

        $id = $request->input('id');

        // 用户信息
        $user = $this->getUser();
        $user_level = $user->level;// 用户等级
        // 推荐人头像和姓名
        $user_name   = $user->name;// 用户名字
        // $user_avatar = !empty($user->avatar_key) ? OSS::instance()->getUrl($user->avatar_key) : '';
        $user_avatar_img = $this->func_get_image($user->avatar, $dir.'tmp_avatar/'.$user->id);// 获取图片
        $user_avatar_img_circle = $this->func_img2Circle($user_avatar_img);// 图片圆形处理

        // 查询商品信息
        $good = Good::query()->where('id', $id)->first();

        // 商品展示图, 第一张
        $cover_image = !empty($good->cover[0]) ? OSS::instance()->getUrl($good->cover[0]) : '';
        $cover_image_height = 618;//图片及边框总高

        // 商品名称
        $good_name = $good->name;
        $theTitle = $this->func_wordwrap('   '.$good_name, 17);
        $title_row_num = count(explode(PHP_EOL, $theTitle));// 标题一共分了多少行
        $title_row_height = $title_row_num*28;//标题高度

        // 获取商品服务标签
        $tags = DB::table('tags')->whereIn('id', explode(',', $good->tag_id))->pluck('name')->all();

        // 推荐分享二维码 小程序码
        $poster = UserGoodsPoster::query()
            ->firstOrCreate([
                'user_id' => $user->id,
                'good_id' => $id,
            ]);
        $key = Manager::getMiniProgramCode($user, $poster);
        // $mini_program_code = $dir . $key;
        $mini_program_code = OSS::instance()->getUrl($key);
        // $mini_program_code = 'D:/_project/php/wedding/public/mini_program/18151/289.png';

        // 商品促销信息
        $good_active = [
            'full_reduction' => null,
            'discount' => null,
            'gift' => null,
            'active_tips' => '',
        ];
        $good_active['gift'] = $good->getGift();
        $isMember = Member::query()->where('user_id', $user->id)->where('shop_id', $good->shop_id)->exists();
        if (!($user_level == 0 || ($user_level == 1 && !$isMember))) {

            $scope = GoodsDiscountScope::query()
                        ->where('type', Good::class)
                        ->where('link_id', $id)
                        ->get();
            if (!$scope->isEmpty()) { 
                $good_active['discount'] = GoodsDiscount::query()
                    ->whereIn('id', $scope->pluck('goods_discount_id')->all())
                    ->get();
            } else {
                $full = FullReductionScope::query()
                    ->where('type', Good::class)
                    ->where('link_id', $id)
                    ->get();
                // if (!is_null($full)) {
                if (!$full->isEmpty()) {
                    $good_active['full_reduction'] = FullReduction::query()
                        ->whereIn('id', $full->pluck('full_reduction_id')->all())
                        ->get();
                }
            }
        }
            
        $tips_height = $full_reduction_height = $discount_height = $gift_height = 0;//商品促销相关高度配置

        // 商品促销价格
        $full_reduction = $discount = '';
        $good_price = $good_active_price = $good->price;
        if (!empty($good_active['full_reduction'])) {
            $full_reduction = $good_active['full_reduction']->first();
            if ($good_price > $full_reduction->limit) {
                $good_active_price = $good_price-$full_reduction->abatement*floor($good_price/$full_reduction->limit);
            }
        }

        if (!empty($good_active['discount'])) {
            $discount = $good_active['discount']->first();
            if ($good_price > $discount->limit) {
                $good_active_price = ($good_price/$discount->limit)*$discount->ratio;
            }
        }

        if ($good_price != $good_active_price) {
            $good_active['active_tips'] = '合伙人、返利会员、员工推荐亲友团专享优惠';
        }

        $good_price = number_format(($good_price/100), 2, '.', '');
        $good_active_price = number_format(($good_active_price/100), 2, '.', '');
        
        $poster_dir = $dir . 'tmp_goods_poster/';
        if (!file_exists($poster_dir)) {
            mkdir($poster_dir, 0777, true);
        }
        $fileName = $poster_dir.$user->id.'_goods_'.$id.'.png';

        //封面图片高度确认
        $poster_height = 0;

        //商品图片+小程序二维码+文字提示（长按或扫描购买）高度
        $poster_good_mini_height = 618+20+150+20+35;//图片高度+间隔+小程序码高度+间隔+文字提示高度
        
        //商品封面和标题
        $img_title_height = 618+32+$title_row_height+3+38+10;//商品图片高度+间隔+多行文字高度+微调+专享价格的高度+间隔
        $poster_height += $img_title_height; 

        if ($good_active['active_tips']) {
            $tips_height = 30;
            $poster_height += 30;
        }

        // 满减
        if (!empty($full_reduction)) {
            $full_reduction_height = 35;
            $poster_height += 41;
        }

        // 折扣
        if (!empty($discount)) {
            $discount_height = 35; 
            $poster_height += 41;
        }

        // 赠品
        if (!empty($good_active['gift'])) {
            $gift = $good_active['gift']->toArray();
            $gift_height = count($gift)*35;
            $poster_height = $poster_height+$gift_height-35+41;
        }

        // 服务
        if ($tags) {
            $tag_icon = $dir . 'tags_icon.png';
            $poster_height += 35;
        }

        if ($poster_good_mini_height > $poster_height) {
            $poster_height = $poster_good_mini_height + 45+119;// 原来高度+间隔+背景图片高度
        }else{
            $poster_height = $poster_height + 45+119 ;// 原来高度+间隔+背景图片高度
        }
        
        //创建画布
        $width  = 618;// 固定
        $height = $poster_height;// 不固定

        $im = imagecreatetruecolor($width, $height);
        
        //填充画布背景色
        $color = imagecolorallocate($im, 255, 255, 255);
        imagefill($im, 0, 0, $color);

        imagepng($im,$fileName);
        
        //字体文件
        $font_file = $dir . "poster.ttf";
        $font_file_bold = $dir . "poster.ttf";
        
        //设定字体的颜色
        $font_color_gray        = ImageColorAllocate($im, 140, 140, 140);//文字灰色
        $font_color_line        = ImageColorAllocate($im, 200, 200, 200);//线段颜色
        $font_color_black       = ImageColorAllocate($im, 28, 28, 28);//黑色
        $font_color_black_light = ImageColorAllocate($im, 59, 59, 59);//浅黑色
        $font_color_red         = ImageColorAllocate($im, 217, 45, 32);//红色
        
        //商品图片
        list($g_w,$g_h) = getimagesize($cover_image);
        $goodImg = imagecreatefromstring(file_get_contents($cover_image));
        imagecopyresized($im, $goodImg, 9, 9, 0, 0, 600, 600, $g_w, $g_h);
        
        //小程序二维码
        list($code_w,$code_h) = getimagesize($mini_program_code);
        $codeImg = imagecreatefromstring(file_get_contents($mini_program_code));
        imagecopyresized($im, $codeImg, 450, 600+20, 0, 0, 150, 150, $code_w, $code_h);

        //长按或扫描购买
        imagettftext($im, 10, 0, 450+6, 620+150+20, $font_color_gray, $font_file, '—— 长按或扫描购买 ——');//
        
        //商品标题  imagettftext函数参考：https://blog.csdn.net/u012767761/article/details/73927728
        imagettftext($im, 18, 0, 9,  650, $font_color_black,   $font_file, $theTitle); // 18号的字体，一行28像素
        imagettftext($im, 12, 0, 9,  650+$title_row_height+3, $font_color_gray, $font_file, "商品促销价：￥".$good_price);
        imagettftext($im, 18, 0, 9, 650+$title_row_height+3+36, $font_color_black, $font_file_bold,  "推荐专享价：");
        imagettftext($im, 28, 0, 145, 650+$title_row_height+3+38, $font_color_red, $font_file, '￥'.$good_active_price);

        if ($good_active['active_tips']) {
            $tips_height = 30;
            imagettftext($im, 12, 0, 9, $img_title_height, $font_color_line, $font_file, '__________________________________________');
            imagettftext($im, 14, 0, 9, $img_title_height+$tips_height, $font_color_gray, $font_file, $good_active['active_tips']);
        }

        // 满减
        if (!empty($full_reduction)) {
            $full_reduction_height = 35;
            $full_reduction_title = $this->cn_row_substr($full_reduction->title);
            imagettftext($im, 16, 0, 9, $img_title_height+$tips_height+$full_reduction_height, $font_color_black, $font_file, '满减');
            imagettftext($im, 13, 0, 66, $img_title_height+$tips_height+$full_reduction_height, $font_color_black_light, $font_file, $full_reduction_title[1]);
            imagettftext($im, 6, 0, 9, $img_title_height+$tips_height+41, $font_color_black_light, $font_file, '           .........................................................................');
        }

        // 折扣
        if (!empty($discount)) {
            $discount_height = 35; 
            $discount_title = $this->cn_row_substr($discount->title);
            imagettftext($im, 16, 0, 9, $img_title_height+$tips_height+$full_reduction_height+$discount_height, $font_color_black, $font_file, '折扣');
            imagettftext($im, 13, 0, 66, $img_title_height+$tips_height+$full_reduction_height+$discount_height, $font_color_black_light, $font_file, $discount_title[1]);
            imagettftext($im, 6, 0, 9, $img_title_height+$tips_height+$full_reduction_height+41, $font_color_black_light, $font_file, '           .........................................................................');
        }

        // 赠品
        if (!empty($good_active['gift'])) {
            $gift = $good_active['gift']->toArray();
            $gift_height = count($gift)*35;
            foreach ($gift as $k => $v) {
                $gift_title = $this->cn_row_substr($v['title']);
                imagettftext($im, 16, 0, 9, $img_title_height+$tips_height+$full_reduction_height+$discount_height+35*($k+1), $font_color_black, $font_file, '赠送');
                imagettftext($im, 13, 0, 66, $img_title_height+$tips_height+$full_reduction_height+$discount_height+35*($k+1), $font_color_black_light, $font_file, $gift_title[1]);
                imagettftext($im, 6, 0, 9, $img_title_height+$tips_height+$full_reduction_height+$discount_height+35*($k)+41, $font_color_black_light, $font_file, '           .........................................................................');
            }
        }

        // 服务
        if ($tags) {
            $tag_icon = $dir . 'tags_icon.png';
            imagettftext($im, 16, 0, 9, $img_title_height+$tips_height+$full_reduction_height+$discount_height+$gift_height+35, $font_color_black, $font_file, '服务');

            list($tag_icon_w, $tag_icon_h) = getimagesize($tag_icon);
            $tag_iconImg = imagecreatefromstring(file_get_contents($tag_icon));

            if (!empty($tags[0])) {
                $tags_1 = $this->cn_row_substr($tags[0], 1, 4);
                imagecopyresized($im, $tag_iconImg, 66, $img_title_height+$tips_height+$full_reduction_height+$discount_height+$gift_height+20, 0, 0, 15, 15, $tag_icon_w, $tag_icon_h);
                imagettftext($im, 13, 0, 66+22, $img_title_height+$tips_height+$full_reduction_height+$discount_height+$gift_height+35, $font_color_black, $font_file, $tags_1[1]);
            }
            if (!empty($tags[1])) {
                $tags_1 = $this->cn_row_substr($tags[1], 1, 4);
                imagecopyresized($im, $tag_iconImg, 181, $img_title_height+$tips_height+$full_reduction_height+$discount_height+$gift_height+20, 0, 0, 15, 15, $tag_icon_w, $tag_icon_h);
                imagettftext($im, 13, 0, 181+22, $img_title_height+$tips_height+$full_reduction_height+$discount_height+$gift_height+35, $font_color_black, $font_file, $tags_1[1]);
            }
            if (!empty($tags[2])) {
                $tags_1 = $this->cn_row_substr($tags[2], 1, 4);
                imagecopyresized($im, $tag_iconImg, 296, $img_title_height+$tips_height+$full_reduction_height+$discount_height+$gift_height+20, 0, 0, 15, 15, $tag_icon_w, $tag_icon_h);
                imagettftext($im, 13, 0, 296+22, $img_title_height+$tips_height+$full_reduction_height+$discount_height+$gift_height+35, $font_color_black, $font_file, $tags_1[1]);
            }
            imagedestroy($tag_iconImg);
        }

        // 用户背景
        $user_bg = $dir . 'user_bg.png';
        list($userBg_w,$userBg_h) = getimagesize($user_bg);
        list($userAvatar_w,$userAvatar_h) = getimagesize($user_avatar_img);
        $userBgImg = imagecreatefromstring(file_get_contents($user_bg));
        $userAvatarImg = imagecreatefromstring(file_get_contents($user_avatar_img_circle));
        imagecopyresized($im, $userBgImg, 9, $img_title_height+$tips_height+$full_reduction_height+$discount_height+$gift_height+60, 0, 0, 600, 119, $userBg_w, $userBg_h);
        imagecopyresized($im, $userAvatarImg, 54, $img_title_height+$tips_height+$full_reduction_height+$discount_height+$gift_height+98, 0, 0, 50, 50, $userAvatar_w, $userAvatar_h);
        imagettftext($im, 14, 0, 118, $img_title_height+$tips_height+$full_reduction_height+$discount_height+$gift_height+118, $font_color_black_light, $font_file, '来自'.$user_name.'的推荐');

        //输出图片
        if($fileName){
            imagepng($im, $fileName);
        }else{
            Header("Content-Type: image/png");
            imagepng($im);
        }
        
        //释放空间
        imagedestroy($im);
        imagedestroy($goodImg);
        imagedestroy($codeImg);
        imagedestroy($userBgImg);
        imagedestroy($userAvatarImg);
        
        $poster_key = str_replace($dir, '', $fileName);
        $oss = OSS::instance();
        $oss->storeFile($poster_key, $fileName);

        $poster->qr_code = $key;
        $poster->url     = OSS::instance()->getUrl($poster_key);
        $poster->save();

        unlink($fileName);
        unlink($user_avatar_img_circle);
        return $this->success(OSS::instance()->getUrl($poster_key));
    }

    /**
     * 分行连续截取字符串
     * @param $str  需要截取的字符串,UTF-8
     * @param int $row  截取的行数
     * @param int $number   每行截取的字数，中文长度
     * @param bool $suffix  最后行是否添加‘...’后缀
     * @return array    返回数组共$row个元素，下标1到$row
     */
    private function cn_row_substr($str, $row = 1, $number = 19, $suffix = true){
        $result = array();
        for ($r=1;$r<=$row;$r++){
            $result[$r] = '';
        }
     
        $str = trim($str);
        if(!$str) return $result;
     
        $theStrlen = strlen($str);
     
        //每行实际字节长度
        $oneRowNum = $number * 3;
        for($r=1;$r<=$row;$r++){
            if($r == $row and $theStrlen > $r * $oneRowNum and $suffix){
                $result[$r] = $this->mg_cn_substr($str,$oneRowNum-6,($r-1)* $oneRowNum).'...';
            }else{
                $result[$r] = $this->mg_cn_substr($str,$oneRowNum,($r-1)* $oneRowNum);
            }
            if($theStrlen < $r * $oneRowNum) break;
        }
     
        return $result;
    }

    /**
     * 按字节截取utf-8字符串
     * 识别汉字全角符号，全角中文3个字节，半角英文1个字节
     * @param $str  需要切取的字符串
     * @param $len  截取长度[字节]
     * @param int $start    截取开始位置，默认0
     * @return string
     */
    private function mg_cn_substr($str,$len,$start = 0){
        $q_str = '';
        $q_strlen = ($start + $len)>strlen($str) ? strlen($str) : ($start + $len);
     
        //如果start不为起始位置，若起始位置为乱码就按照UTF-8编码获取新start
        if($start and json_encode(substr($str,$start,1)) === false){
            for($a=0;$a<3;$a++){
                $new_start = $start + $a;
                $m_str = substr($str,$new_start,3);
                if(json_encode($m_str) !== false) {
                    $start = $new_start;
                    break;
                }
            }
        }
     
        //切取内容
        for($i=$start;$i<$q_strlen;$i++){
            //ord()函数取得substr()的第一个字符的ASCII码，如果大于0xa0的话则是中文字符
            if(ord(substr($str,$i,1))>0xa0){
                $q_str .= substr($str,$i,3);
                $i+=2;
            }else{
                $q_str .= substr($str,$i,1);
            }
        }
        return $q_str;
    }


    /**
     * 按照指定长度对字符串进行折行处理
     *
     * @author baoyang<571265160@qq.com>
     * @date   2020-06-20
     * @param  string     $str        [要进行折行的字符串]
     * @param  integer    $num        [行宽度]
     * @param  string     $line_break [换行符, 默认\n]
     * @return string                 [处理后的字符串]
     */
    private function func_wordwrap($str = '', $num = 0, $line_break = PHP_EOL){

        preg_match_all("/./u", $str, $arr);//将所有字符转成单个数组
        
        $strstr = '';
        $width  = 0;
        $arr    = $arr[0];
        foreach($arr as $key => $string){
            $strlen = strlen($string);//计算当前字符的长度，一个字母的长度为1，一个汉字的长度为3
            $strlen == 3 ? $width += 1 : $width += 0.5;
            $strstr .= $string;
            
            //计算当前字符的下一个
            if(array_key_exists($key + 1, $arr)){
                $_strlen = strlen($arr[$key + 1]);
                $strlen == 3 ? $_width = 1 : $_width = 0.5;
                if($width + $_width > $num){
                    $width = 0;
                    $strstr .= $line_break;
                }
            }
        }
        return $strstr;
    }

    /**
     * 图片圆角处理
     *
     * @author baoyang<571265160@qq.com>
     * @date   2020-06-20
     * @param  string     $url [图片地址]
     * @param  integer    $h   [高]
     * @param  integer    $w   [宽]
     * @return string          [处理后的图片地址]
     */
    private function func_img2Circle($url = '', $h = 60, $w = ''){
        $des_h = $h; //高度
        $des_w = $w ? $w : $h; //宽度
        $srcarr = getimagesize($url);
        //处理图片创建函数和图片输出函数
        switch($srcarr[2]){
            case 1://gif
                $imagecreatefrom = 'imagecreatefromgif';
                $imageout = 'imagegif';
                break;
            case 2://jpg
                $imagecreatefrom = 'imagecreatefromjpeg';
                $imageout = 'imagejpeg';
                break;
            case 3://png
                $imagecreatefrom = 'imagecreatefrompng';
                $imageout = 'imagepng';
                break;
        }
        // 创建原图资源
        $src_img = $imagecreatefrom($url);
        //获取原图的宽高
        $src_w = imagesx($src_img);
        $src_h = imagesy($src_img);
        // 计算缩放比例（用原图片的宽高分别处以对应目的图片的宽高，选择比例大的作为基准进行缩放）
        $scale = ($src_w/$des_w)>($src_h/$des_h)?($src_w/$des_w):($src_h/$des_h);
        //计算实际缩放时目的图的宽高（向下取整）
        $des_w = floor($src_w/$scale);
        $des_h = floor($src_h/$scale);
        //创建画布
        $des_img = imagecreatetruecolor($des_w, $des_h);
        //设置缩放起点
        $des_x = 0;
        $des_y = 0;
        $src_x = 0;
        $src_y = 0;
        //缩放
        imagecopyresampled($des_img, $src_img, $des_x, $des_y, $src_x, $src_y, $des_w, $des_h, $src_w, $src_h);
        //输出图片
        //header('content-type:image/jpeg');
        //获取源文件的文件名
        $t_file = basename($url);
        // 获取源文件的路径名
        $t_dir = dirname($url);
        // 生成保存文件的文件路径名
        $s_file = $t_dir.'/'.$t_file;
        $imageout($des_img,$s_file);

        list($src_w, $src_h) = getimagesize($s_file);
        $w = $src_w;  $h=$src_h; // original size
        $original_path= $s_file;
        //$dest_path = $path.md5($openid.$uid)."tx".'.png';
        $src = imagecreatefromstring(file_get_contents($original_path));
        $newpic = imagecreatetruecolor($w,$h);
        imageantialias($newpic, true);
        imagealphablending($newpic,false);
        $transparent = imagecolorallocatealpha($newpic, 255, 255, 255, 127);
        $r=$w/2;
        for($x=0;$x<$w;$x++)
            for($y=0;$y<$h;$y++){
                $c = imagecolorat($src,$x,$y);
                $_x = $x - $w/2;
                $_y = $y - $h/2;
                if((($_x*$_x) + ($_y*$_y)) < ($r*$r)){
                    imagesetpixel($newpic,$x,$y,$c);
                }else{
                    imagesetpixel($newpic,$x,$y,$transparent);
                }
            }
        imagesavealpha($newpic, true);
        imagepng($newpic, $s_file);
        imagedestroy($newpic);
        imagedestroy($src);

        return $s_file;
    }

    /**
     * 图片保存到本地
     *
     * @author baoyang<571265160@qq.com>
     * @date   2020-06-20
     * @param  string     $img_url [图片地址]
     * @param  string     $dir     [存放文件夹路径]
     * @return string              [本地文件路径]
     */
    private function func_get_image($img_url = '', $dir = 'other'){
        
        $header = [
            'User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:45.0) Gecko/20100101 Firefox/45.0',    
            'Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',    
            'Accept-Encoding: gzip, deflate',
        ];

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $img_url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($curl, CURLOPT_ENCODING, 'gzip');
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        $data = curl_exec($curl);
        $code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        curl_close($curl);

        if ($code == 200) {//把URL格式的图片转成base64_encode格式的！    
            $imgBase64Code = "data:image/jpeg;base64," . base64_encode($data);
        }else{
            return false;
        }

        $img_content = $imgBase64Code;//图片内容

        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $img_content, $result)){ 
            $type = $result[2];//得到图片类型png?jpg?gif? 
            $path = $dir;
            
            if(!file_exists($path))    
                mkdir($path, 0755, true);

            $new_file = $path . md5($img_url) . '.' . $type;

            if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $img_content)))){
                return $new_file; 
            }
        } 

    }

}
